package model

import (
	"context"
	"fmt"
	"time"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ SysUserModel = (*customSysUserModel)(nil)

type (
	// SysUserModel is an interface to be customized, add more methods here,
	// and implement the added methods in customSysUserModel.
	SysUserModel interface {
		sysUserModel
		RowBuilder() squirrel.SelectBuilder
		Truncate(ctx context.Context)
		FindAll(ctx context.Context) ([]*SysUser, error)
		FindAllEx(Current int64, PageSize int64) (*[]SysUserList, error)
		Count() (int64, error)
	}

	SysUserList struct {
		Id             int64     `db:"id"`               // 编号
		Name           string    `db:"name"`             // 用户名
		NickName       string    `db:"nick_name"`        // 昵称
		Avatar         string    `db:"avatar"`           // 头像
		Password       string    `db:"password"`         // 密码
		Salt           string    `db:"salt"`             // 加密盐
		Email          string    `db:"email"`            // 邮箱
		Mobile         string    `db:"mobile"`           // 手机号
		Status         int64     `db:"status"`           // 状态  0：禁用   1：正常
		DeptId         int64     `db:"dept_id"`          // 机构ID
		JobId          int64     `db:"job_id"`           // 岗位ID
		CreateBy       string    `db:"create_by"`        // 创建人
		CreateTime     time.Time `db:"create_time"`      // 创建时间
		LastUpdateBy   string    `db:"last_update_by"`   // 更新人
		LastUpdateTime time.Time `db:"last_update_time"` // 更新时间
		DelFlag        int64     `db:"del_flag"`         // 是否删除  -1：已删除  0：正常
		JobName        string    `db:"job_name"`
		DeptName       string    `db:"dept_name"`
		RoleName       string    `db:"role_name"`
		RoleId         int64     `db:"role_id"`
	}

	customSysUserModel struct {
		*defaultSysUserModel
	}
)

// NewSysUserModel returns a model for the database table.
func NewSysUserModel(conn sqlx.SqlConn, c cache.CacheConf) SysUserModel {
	return &customSysUserModel{
		defaultSysUserModel: newSysUserModel(conn, c),
	}
}

func (m *defaultSysUserModel) RowBuilder() squirrel.SelectBuilder {
	return squirrel.Select(sysUserRows).From(m.table)
}

func (m defaultSysUserModel) Truncate(ctx context.Context) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err == nil {
		var resp []*SysUser
		err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
		if err == nil {
			for _, r := range resp {
				m.Delete(ctx, r.Id)
			}
			m.ExecNoCacheCtx(ctx, fmt.Sprintf("TRUNCATE %s", m.tableName()))
		}
	}
}

func (m defaultSysUserModel) FindAll(ctx context.Context) ([]*SysUser, error) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err != nil {
		return nil, nil
	}

	var resp []*SysUser
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}

func (m *defaultSysUserModel) FindAllEx(Current int64, PageSize int64) (*[]SysUserList, error) {

	//query := fmt.Sprintf("select %s from %s limit ?,?", sysUserRows, m.table)
	query := "select sys_user.*, ifnull(sj.job_name,'') as job_name, ifnull(sd.name ,'')as dept_name, ifnull(sys_role.name,'') as role_name,ifnull(sys_role.id ,'1')as role_id from sys_user   left join sys_user_role sur on sys_user.id = sur.user_id   left join sys_role on sur.role_id = sys_role.id    left join sys_job sj on sys_user.job_id = sj.id left join sys_dept sd on sys_user.dept_id = sd.id limit ?,?"
	var resp []SysUserList
	err := m.CachedConn.QueryRowsNoCache(&resp, query, (Current-1)*PageSize, PageSize)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultSysUserModel) Count() (int64, error) {
	query := fmt.Sprintf("select count(*) as count from %s", m.table)

	var count int64
	err := m.CachedConn.QueryRowNoCache(&count, query)

	switch err {
	case nil:
		return count, nil
	case sqlc.ErrNotFound:
		return 0, ErrNotFound
	default:
		return 0, err
	}
}
